//axios-init.js 
import axios from 'axios';
import router from '../router/index'

import { indexUrl } from '../config/index'

const service = axios.create({
    baseURL: indexUrl,
    timeout: 50000
})

// 添加请求拦截器，在请求头中加token
service.interceptors.request.use(
    config => {
        if (localStorage.Authorization) { // 判断是否存在Authorization，如果存在的话，则每个http header都加上Authorization
            const token = localStorage.Authorization
                // const newtoken = token.substring(1, token.length - 1)
                // console.log(newtoken);
            config.headers['Authorization'] = token;
        }
        return config
    },
    err => {
        return Promise.reject(err)
    })


// http response 拦截器
service.interceptors.response.use(
    response => {
        if (response.data.errno === 999) {
            router.replace('/');
            console.log("token过期");
        }
        return response.data;
    },
    error => {
        return Promise.reject(error);
    }
);


export default service